package com.hhit.zhgd.task

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
import com.hhit.zhgd.component.FileProperties
import com.hhit.zhgd.dao.ZhgWarnListMapper
import com.hhit.zhgd.dao.ZhgdAlertMapper
import com.hhit.zhgd.dao.ZhgdSmBallAlarmMapper
import com.hhit.zhgd.domain.entity.ZhgdAlert
import com.hhit.zhgd.domain.entity.ZhgdSmBallAlarm
import com.hhit.zhgd.domain.entity.ZhgdWarnList
import jakarta.annotation.Resource
import org.quartz.JobExecutionContext
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.scheduling.quartz.QuartzJobBean
import java.io.File
import java.text.SimpleDateFormat
import java.util.*

class DeleteTask:QuartzJobBean() {

    private val log= LoggerFactory.getLogger(DeleteTask::class.java)

    @Autowired
    private var alertMapper:ZhgdAlertMapper?=null
    @Autowired
    private var smBallAlarmMapper: ZhgdSmBallAlarmMapper?=null
    @Autowired
    private var warnListMapper:ZhgWarnListMapper?=null
    @Resource
    private var fileProperties: FileProperties?=null
    override fun executeInternal(context: JobExecutionContext) {
        log.info("DeleteTask Executing.....")
        //获取七天前的日期
        val startTime = getTime(fileProperties?.saveDay)

        val zhgdAlerts = alertMapper!!.selectList(
            LambdaQueryWrapper<ZhgdAlert>().last(
                "where TO_DAYS(create_time) <= TO_DAYS('$startTime')"
            )
        )

        val zhgdSmBallAlarms = smBallAlarmMapper!!.selectList(
            LambdaQueryWrapper<ZhgdSmBallAlarm>().last(
                "where TO_DAYS(create_time) <= TO_DAYS('$startTime')"
            )
        )

        for ( zhgdAlert in zhgdAlerts) {
            if (zhgdAlert.warnImage?.isNotBlank()==true) {
                val warnImage: String = fileProperties?.parentPath + zhgdAlert.warnImage
                val taggingImage: String = fileProperties?.parentPath + zhgdAlert.taggingImage
                File(warnImage).delete()
                File(taggingImage).delete()
            }
            alertMapper?.deleteById(zhgdAlert.id)
            warnListMapper?.delete(LambdaQueryWrapper<ZhgdWarnList>().eq(ZhgdWarnList::alertId, zhgdAlert.id))
        }

        for (zhgdSmBallAlarm in zhgdSmBallAlarms) {
            val img: String = fileProperties?.parentPath + zhgdSmBallAlarm?.imageFile
            File(img).delete()
            smBallAlarmMapper?.deleteById(zhgdSmBallAlarm.id)
        }
    }

    private fun getTime(num: Int?): String? {
        if (num==null) {
            return ""
        }
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
        val calendar = Calendar.getInstance()
        calendar[Calendar.DATE] = calendar[Calendar.DATE] - num
        return sdf.format(calendar.time)
    }
}